package com.framework.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.fasterxml.jackson.databind.ObjectMapper;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class HttpConnectionPostUtils {

	//http://localhost:8080/hewke-con/dataclient/isEnUser.shtml?id=1
	public static String post_url="";
	public static String getPost_url() {
		return post_url;
	}

	public static void setPost_url(String post_url) {
		HttpConnectionPostUtils.post_url = post_url;
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
//		readContentFromPost(null);
	}

/*	public static Map<String, Object> nametoMap(String username) throws IOException {
		Map<String, Object> datacentermap = null;
		if (username!=null||!username.trim().equals("")) {
			StringBuffer stringBuffer=HttpConnectionPostUtils.readContentFromPost(username);
			if (stringBuffer.toString().length()>6) {
				int start=stringBuffer.toString().indexOf("[");
				int end=stringBuffer.toString().indexOf("]");
				String values=stringBuffer.substring(start,end+1);
				JSONArray jsonArray=JSONArray.fromObject(values);
				System.out.println(jsonArray);
				com.alibaba.druid.support.json.JSONUtils.parse(jsonArray.toString());
				datacentermap=JsonUtil.jsonToMap(jsonArray.get(0).toString());
				
			}
		}
		return datacentermap;
	}*/
	
//	public static Map<String, Object> namet1oMap(String cellphone) throws IOException {
//		Map<String, Object> datacentermap = null;
//		if (cellphone!=null||!cellphone.trim().equals("")) {
//			StringBuffer stringBuffer=HttpConnectionPostUtils.sendPostFromUrl(cellphone, true);
//			if (stringBuffer.toString().length()>6) {
//				datacentermap=JsonUtil.jsonToMap(stringBuffer.toString());
//			}
//		}
//		return datacentermap;
//	}
	
	public static ArrayList<Map<String, Object>> nametoMap(String cellphone,boolean flag) throws IOException {
		
		ArrayList<Map<String, Object>> arrayList=new ArrayList<>();
		Map<String, Object> datacentermap = null;
		if (cellphone!=null||!cellphone.trim().equals("")) {
			StringBuffer stringBuffer=HttpConnectionPostUtils.sendPostFromUrl(cellphone, true);
			if (stringBuffer.toString().length()>6) {
				JSONArray jsonarray = JSONArray.fromObject(stringBuffer.toString());  
		        
		        for (int i = 0; i < jsonarray.size(); i++) {
		        	 Map<String, Object> map=(Map<String, Object>) jsonarray.get(i);
		        	 arrayList.add(i, map);
				}
				return arrayList;
			}
		}
		return null;
	}
	
	public static ArrayList<Map<String, Object>> getDataFromSB(StringBuffer stringBuffer) throws IOException {
		ArrayList<Map<String, Object>> arrayList=new ArrayList<>();
		Map<String, Object> datacentermap = null;
			if (stringBuffer.toString().length()>6) {
				JSONArray jsonarray = JSONArray.fromObject(stringBuffer.toString());  
		        for (int i = 0; i < jsonarray.size(); i++) {
		        	 Map<String, Object> map=(Map<String, Object>) jsonarray.get(i);
		        	 arrayList.add(i, map);
				}
				return arrayList;
			}
		return null;
	}
	
	
	public static StringBuffer readContentFromPost(String url) throws IOException {
		// Post请求的url，与get不同的是不需要带参数
		URL postUrl = new URL(url);
		postUrl.getProtocol();
		// 打开连接
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		// 设置是否向connection输出，因为这个是post请求，参数要放在
		// http正文内，因此需要设为true
		connection.setDoOutput(true);
		// Read from the connection. Default is true.
		connection.setDoInput(true);
		// 默认是 GET方式
		connection.setRequestMethod("POST");

		// Post 请求不能使用缓存
		connection.setUseCaches(false);

		connection.setInstanceFollowRedirects(true);

		// 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的
		// 意思是正文是urlencoded编码过的form参数，下面我们可以看到我们对正文内容使用URLEncoder.encode
		// 进行编码
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		// 连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
		// 要注意的是connection.getOutputStream会隐含的进行connect。
		connection.connect();
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		// The URL-encoded contend
		// 正文，正文内容其实跟get的URL中 '? '后的参数字符串一致
//		if (username!=null) {
//			String content = "username=" + URLEncoder.encode(username, "UTF-8");
//			out.writeBytes(content);
//
//			out.flush();
//			out.close();
//		}
		
		// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
		

		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
		String line;

		StringBuffer sb = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
			
			sb.append(line);
		}

		reader.close();
		connection.disconnect();
		return sb;
	}

	public static StringBuffer readContentFromPost(String url,String username) throws IOException {
		// Post请求的url，与get不同的是不需要带参数
		URL postUrl = new URL(url);
		postUrl.getProtocol();
		// 打开连接
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		// 设置是否向connection输出，因为这个是post请求，参数要放在
		// http正文内，因此需要设为true
		connection.setDoOutput(true);
		// Read from the connection. Default is true.
		connection.setDoInput(true);
		// 默认是 GET方式
		connection.setRequestMethod("POST");

		// Post 请求不能使用缓存
		connection.setUseCaches(false);

		connection.setInstanceFollowRedirects(true);

		// 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的
		// 意思是正文是urlencoded编码过的form参数，下面我们可以看到我们对正文内容使用URLEncoder.encode
		// 进行编码
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		// 连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
		// 要注意的是connection.getOutputStream会隐含的进行connect。
		connection.connect();
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		// The URL-encoded contend
		// 正文，正文内容其实跟get的URL中 '? '后的参数字符串一致
		if (username!=null) {
			String content = "username=" + URLEncoder.encode(username, "UTF-8");
			out.writeBytes(content);

			
		}
		out.flush();
		out.close();
		// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
		

		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
		String line;

		StringBuffer sb = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
			
			sb.append(line);
		}

		reader.close();
		connection.disconnect();
		return sb;
	}
	
	/**
	 * 
	 *	@author 李品良
	 * @param url
	 * @param map
	 * @return
	 * @throws IOException
	 */
	public static StringBuffer readContentFromPost(String url,HashMap<String, Object> hashMap) throws IOException {
		URL postUrl = new URL(url);
		postUrl.getProtocol();
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(true);
		// 进行编码
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		// 连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
		// 要注意的是connection.getOutputStream会隐含的进行connect。
		connection.connect();
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		String content="";
		// The URL-encoded contend
		// 正文，正文内容其实跟get的URL中 '? '后的参数字符串一致
		if (hashMap!=null) {
			Set<String> set=hashMap.keySet();
			Iterator<String> iterator=set.iterator();
			while (iterator.hasNext()) {
				String key = (String) iterator.next();
				content+= key +"=" + URLEncoder.encode(hashMap.get(key).toString(), "UTF-8")+"&";
			}
			//重装url
			out.writeBytes(content);
		}
		out.flush();
		out.close();
		// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
		

		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
		String line;

		StringBuffer sb = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
			
			sb.append(line);
		}

		reader.close();
		connection.disconnect();
		return sb;
	}
	
	/**
	 * 登陆使用，flag，没用
	 *	@author 李品良
	 * @param cellphone 登陆手机号码
	 * @param flag
	 * @return
	 * @throws IOException
	 */
	public static StringBuffer sendPostFromUrl(String cellphone,boolean flag) throws IOException {
		// Post请求的url，与get不同的是不需要带参数
		URL postUrl = new URL(post_url);
		
		
		postUrl.getProtocol();
		// 打开连接
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		// 设置是否向connection输出，因为这个是post请求，参数要放在
		// http正文内，因此需要设为true
		connection.setDoOutput(true);
		// Read from the connection. Default is true.
		connection.setDoInput(true);
		// 默认是 GET方式
		connection.setRequestMethod("POST");

		// Post 请求不能使用缓存
		connection.setUseCaches(false);

		connection.setInstanceFollowRedirects(true);

		// 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的
		// 意思是正文是urlencoded编码过的form参数，下面我们可以看到我们对正文内容使用URLEncoder.encode
		// 进行编码
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		// 连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
		// 要注意的是connection.getOutputStream会隐含的进行connect。
		connection.connect();
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		// The URL-encoded contend
		// 正文，正文内容其实跟get的URL中 '? '后的参数字符串一致
		String content = "cellphone=" + URLEncoder.encode(cellphone, "UTF-8");
		;
		// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
		out.writeBytes(content);

		out.flush();
		out.close();

		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
		String line;

		StringBuffer sb = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
			
			sb.append(line);
		}

		reader.close();
		connection.disconnect();
		return sb;
	}

	
	public static StringBuffer sendPostFromUrl(String post_url,String pronvince) throws IOException {
		// Post请求的url，与get不同的是不需要带参数
		URL postUrl = new URL(post_url);
		
		
		postUrl.getProtocol();
		// 打开连接
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		// 设置是否向connection输出，因为这个是post请求，参数要放在
		// http正文内，因此需要设为true
		connection.setDoOutput(true);
		// Read from the connection. Default is true.
		connection.setDoInput(true);
		// 默认是 GET方式
		connection.setRequestMethod("POST");

		// Post 请求不能使用缓存
		connection.setUseCaches(false);

		connection.setInstanceFollowRedirects(true);

		// 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的
		// 意思是正文是urlencoded编码过的form参数，下面我们可以看到我们对正文内容使用URLEncoder.encode
		// 进行编码
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		// 连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
		// 要注意的是connection.getOutputStream会隐含的进行connect。
		connection.connect();
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		// The URL-encoded contend
		// 正文，正文内容其实跟get的URL中 '? '后的参数字符串一致
		String content = "pronvince=" + URLEncoder.encode(pronvince, "UTF-8");
		;
		// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
		out.writeBytes(content);

		out.flush();
		out.close();

		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
		String line;

		StringBuffer sb = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
			
			sb.append(line);
		}

		reader.close();
		connection.disconnect();
		return sb;
	}

	
	
	 // Json生成Map  
    public Map<String, Object> jsonToMap(String jsonString) throws JSONException {  
        //JSONObject必须以"{"开头  
        JSONObject jsonObject = new JSONObject();  
        Map<String, Object> resultMap = new HashMap<String, Object>();  
        Iterator<String> iter = jsonObject.keys();  
        String key=null;  
        Object value=null;  
        while (iter.hasNext()) {  
            key=iter.next();  
            value=jsonObject.get(key);  
            resultMap.put(key, value);  
        }  
        System.out.println(resultMap);  
        /* 
         * 打印结果{map={"sex":"female","age":"23","name":"Alexia"}, employ={"sex":"female","age":"24","name":"wjl"}} 
         */  
        return resultMap;  
    }  
}
